//
//  YuYueListViewController.m
//  NOAHWM
//
//  Created by Ryan on 13-6-9.
//  Copyright (c) 2013年 Ryan. All rights reserved.
//

#import "YuYueListViewController.h"
#import "YuYueListTableCell.h"
#import "NYMemberCenterDataManager.h"
#import "NYProductOrder.h"
#import "JSON.h"
#import "NYProduct.h"
#import "ProductDetailViewController.h"

#define kYuYueListDownloaderKey     @"YuYueListDownloaderKey"
#define kDeleteYuYueDownloaderKey   @"DeleteYuYueDownloaderKey"

static NSInteger kNumOfPage = 10;
static NSInteger kInitPageNum = 1;
static NSInteger kCurrentPageNum = 1;
static NSInteger kAllNumOfPage = 10001;

@interface YuYueListViewController ()

@property (nonatomic, retain) NSMutableArray *productOrders;
@property (nonatomic, retain) NSMutableArray *filterOrders;
@property (nonatomic, copy) NSString *deleteId;

@end

@implementation YuYueListViewController

@synthesize yuyueTableView;
@synthesize productOrders;
@synthesize moreView;
@synthesize deleteId;
@synthesize listType;
@synthesize filterOrders;
@synthesize isFromRightMenu;
@synthesize placeHolderImageView;
@synthesize isFromEdit;
@synthesize yuyueEnter;

- (MoreView *)moreView
{
    if(nil == moreView)
    {
        NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"MoreView" owner:self options:nil];
        moreView = [[nibs lastObject] retain];
        moreView.delegate = self;
    }
    return moreView;
}

#pragma mark - Public methods
- (void)callServerToGetOnlineProductOrdersList:(NSString *)accountId
                                          flag:(NSInteger)flag
                                        pageNo:(NSInteger)pageNo
                                      pageSize:(NSInteger)pageSize
                                    updateTime:(NSString *)updateTime
{
    NSString *suburl = [NSString stringWithFormat:kYuyueListUrl,@"jsonp",accountId,flag,pageNo,pageSize,updateTime];
    if(self.yuyueEnter == kDetailPageEnter)
    {
        suburl = [suburl stringByAppendingString:@"app000039"];
    }
    else if(self.yuyueEnter == kYuyueAlertEnter)
    {
        suburl = [suburl stringByAppendingString:@"app000037"];
    }
    else
    {
        suburl = [suburl stringByAppendingString:@"app000048"];
    }
    NSString *url = [NSString stringWithFormat:@"%@%@",kServerAddress,suburl];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[RYDownloaderManager sharedManager] requestDataByGetWithURLString:url delegate:self purpose:kYuYueListDownloaderKey];
}

- (void)refreshProductOrdersList
{
    kCurrentPageNum = kInitPageNum;
    [self callServerToGetOnlineProductOrdersList:[NYMemberCenterDataManager sharedManager].loginMember.accountId flag:0 pageNo:kCurrentPageNum pageSize:kNumOfPage updateTime:@""];
}

- (void)filterList
{
    self.filterOrders = [NSArray arrayWithArray:self.productOrders];
//    if(self.listType == kListAll)
//    {
//        self.filterOrders = [NSArray arrayWithArray:self.productOrders];
//    }
//    else
//    {
//        //设置当前日期后3个月前的日期
//        NSDate *nowDate = [NSDate date];
//        NSDateComponents *component = [[NSCalendar currentCalendar] components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit fromDate:nowDate];
//        [component setMonth:[component month]-3];
//        NSDate *before3MonthDate = [[NSCalendar currentCalendar] dateFromComponents:component];
//        
//        self.filterOrders = [NSMutableArray array];
//        for(NYProductOrder *nypo in self.productOrders)
//        {
//             //"booking_time__c": "2013-06-05 13:46:28",
//            NSString *dateString = nypo.booking_time__c;
//            NSDate *nypoDate = [NSDate dateFromStringByFormat:@"yyyy-MM-dd HH:mm:ss" string:dateString];
//            if(self.listType == kListRecent3Month)
//            {
//                if([nypoDate compare:before3MonthDate] == NSOrderedDescending && [nypoDate compare:nowDate] == NSOrderedAscending)
//                    [self.filterOrders addObject:nypo];
//            }
//            else if(self.listType == kListBefore3Month)
//            {
//                if([nypoDate compare:before3MonthDate] == NSOrderedAscending)
//                    [self.filterOrders addObject:nypo];
//            }
//        }
//    }
}

#pragma mark - Notification methods
- (void)filterYuyueListWithNotification:(NSNotification *)notification
{
    self.filterOrders = [NSMutableArray array];
    self.yuyueTableView.hidden = YES;
    self.placeHolderImageView.hidden = NO;
    self.placeHolderImageView.image = [UIImage imageNamed:@"loading_data.png"];
    
    /**
     flag=2     pageSize > 10000  3个月前；
     flag=3     pageSize > 10000  3个月后；
     flag!=2 和flag!=3  pageSize=10分页查询；
     flag!=2 和flag!=3  pageSize=10000查询全部
     */
    
    //0-最近3个月 1-3个月前 2-全部
    NSInteger index = [notification.object integerValue];
    self.listType = (YuYueListType)index;
    NSInteger flag = 0;
    NSInteger pageNum = kNumOfPage;
    if(self.listType == kListBefore3Month)
    {
        flag = 2;
        pageNum = kAllNumOfPage;
    }
    else if(self.listType == kListRecent3Month)
    {
        flag = 3;
        pageNum = kAllNumOfPage;
    }
    else
    {
        flag = 0;
        pageNum = kNumOfPage;
    }
    kCurrentPageNum = kInitPageNum;
    [self callServerToGetOnlineProductOrdersList:[NYMemberCenterDataManager sharedManager].loginMember.accountId flag:flag pageNo:kCurrentPageNum pageSize:pageNum updateTime:@""];
//    [self filterList];
//    [self.yuyueTableView reloadData];
}

- (void)refreshYuyuProductsWithNotification:(NSNotification *)notification
{
    self.listType = kListAll;
    [self refreshProductOrdersList];
}

#pragma mark - BaseViewController methods
- (void)leftItemTapped
{
    if(!self.isFromRightMenu)
    {
        if(!self.isFromEdit)
            [self.navigationController popViewControllerAnimated:YES];
        else
            [self.navigationController popToViewController:[[self.navigationController viewControllers] objectAtIndex:1] animated:YES];
    }
    else
        [super leftItemTapped];
}

- (void)rightItemTapped
{
    if(!self.isFromRightMenu)
    {
        NSArray *properties = [NSArray arrayWithObject:@"Call"];
        NSMutableDictionary *filterInfo = [NSMutableDictionary dictionary];
        [filterInfo setObject:properties forKey:kFilterPropertiesKey];
        [filterInfo setObject:[NSNumber numberWithInt:kLocationRight] forKey:kFilterLocationType];
        [filterInfo setObject:[NSNumber numberWithInteger:kProYuyueListRightFilter] forKey:kFilterTypeKey];
        [[NSNotificationCenter defaultCenter] postNotificationName:kShowFilterViewNotification object:nil userInfo:filterInfo];
    }
    else
        [super rightItemTapped];
}

- (void)extraItemTapped
{
    NSArray *properties = [NSArray arrayWithObjects:@"最近三个月",@"三个月前",@"全部", nil];
    NSMutableDictionary *filterInfo = [NSMutableDictionary dictionary];
    [filterInfo setObject:properties forKey:kFilterPropertiesKey];
     [filterInfo setObject:[NSNumber numberWithInt:kLocationCenter] forKey:kFilterLocationType];
    [filterInfo setObject:[NSNumber numberWithInteger:KProYuyueListFilter] forKey:kFilterTypeKey];
    [[NSNotificationCenter defaultCenter] postNotificationName:kShowFilterViewNotification object:nil userInfo:filterInfo];
}

#pragma mark - UIViewController methods

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(filterYuyueListWithNotification:) name:kFilterProYuyueListNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshYuyuProductsWithNotification:) name:kRefreshYuyueProductsNotification object:nil];
    [self setNaviTitle:@"预约产品列表"];
    
    if(!self.isFromRightMenu)
    {
        [self setLeftNaviItemWithTitle:nil imageName:@"Icon_Back"];
        [self setRightNaviItemWithTitle:nil imageName:@"Icon_Dial"];
    }
    self.headerView.extraButton.hidden = NO;

    [self refreshYuyuProductsWithNotification:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.isViewLoaded && !self.view.window)
    {
        [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
        [[NSNotificationCenter defaultCenter] removeObserver:self];
        self.view = nil;
        self.yuyueTableView = nil;
        self.moreView = nil;
        self.placeHolderImageView = nil;
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    self.yuyueTableView = nil;
    self.moreView = nil;
    self.placeHolderImageView = nil;
}

- (void)dealloc
{
    [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [placeHolderImageView release];
    [deleteId release];
    [productOrders release];
    [filterOrders release];
    [yuyueTableView release];
    [moreView release];
    [super dealloc];
}

#pragma mark - MoreViewDelegate method
- (void)didMoreViewClicked
{
    
    /**
     flag=2     pageSize > 10000  3个月前；
     flag=3     pageSize > 10000  3个月后；
     flag!=2 和flag!=3  pageSize=10分页查询；
     flag!=2 和flag!=3  pageSize=10000查询全部
     */
    
    //0-最近3个月 1-3个月前 2-全部
    NSInteger flag = 0;
    NSInteger pageNum = kNumOfPage;
    if(self.listType == kListBefore3Month)
    {
        flag = 2;
        pageNum = kAllNumOfPage;
    }
    else if(self.listType == kListRecent3Month)
    {
        flag = 3;
        pageNum = kAllNumOfPage;
    }
    else
    {
        flag = 0;
        pageNum = kNumOfPage;
    }
    
    [self callServerToGetOnlineProductOrdersList:[NYMemberCenterDataManager sharedManager].loginMember.accountId flag:flag pageNo:++kCurrentPageNum pageSize:pageNum updateTime:@""];
}

#pragma mark - UITableViewDataSource methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.filterOrders.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentify = @"cellIdentify";
    YuYueListTableCell *cell = (YuYueListTableCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentify];
    if(nil == cell)
    {
        NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"YuYueListTableCell" owner:self options:nil];
        cell = [nibs lastObject];
        
        UIImageView *bgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg_selection@2x.png"]];
        cell.selectedBackgroundView = bgView;
        [bgView release];
        
    }
    NYProductOrder *nypo = [self.filterOrders objectAtIndex:indexPath.row];
    cell.nameLabel.text = nypo.public_product_name;
    cell.moneyLabel.text = [NSString stringWithFormat:@"%@ %@",nypo.productcurrency,nypo.amount];
    cell.statusLabel.text = nypo.stagename;
    
    NSString *dateString = @"";
    if(nypo.booking_time__c && ![nypo.booking_time__c isEqualToString:@""])
    {
        dateString = [[nypo.booking_time__c componentsSeparatedByString:@" "] objectAtIndex:0];
    }
    
    cell.dateLabel.text = dateString;
    cell.shouyilvLabel.text = nypo.expect_yield;
    return cell;
}


#pragma mark - UITableViewDelegate methods
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kYuYueListTableCellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NYProductOrder *nypo = [self.filterOrders objectAtIndex:indexPath.row];
    
    if(![nypo.iscanread isEqualToString:@"1"])
    {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        return;
    }
    
    if(self.isFromRightMenu)
    {
        NYProduct *nyp = [[NYProduct alloc] init];
        nyp.sf_opportunity_id = nypo.sf_opportunity_id;
        nyp.public_product_name = nypo.public_product_name;;
        ProductDetailViewController *pdvc = [[ProductDetailViewController alloc] init];
        pdvc.product = nyp;
        pdvc.isForYuYue = YES;
        [self.navigationController pushViewController:pdvc animated:YES];
        [pdvc release];
        [nyp release];
    }
    else
    {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        NYProduct *nyp = [[NYProduct alloc] init];
        nyp.sf_opportunity_id = nypo.sf_opportunity_id;
        nyp.public_product_name = nypo.public_product_name;
        [[NSNotificationCenter defaultCenter] postNotificationName:kShowYuyueDetailViewNotification object:nyp];
        [nyp release];
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    NYProductOrder *nypo = [self.filterOrders objectAtIndex:indexPath.row];
    if([nypo.stagename_code isEqualToString:@"00010007"])
        return YES;
    else
        return NO;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //add code here for when you hit delete
        NYProductOrder *nypo = [self.filterOrders objectAtIndex:indexPath.row];
        self.deleteId = nypo.sf_opportunity_id;
        NSString *suburl = [NSString stringWithFormat:kDeleteYuYueUrl,@"jsonp",[NYMemberCenterDataManager sharedManager].loginMember.accountId,nypo.sf_opportunity_id];
        suburl = [suburl stringByAppendingString:@"app000040"];
        NSString *url = [NSString stringWithFormat:@"%@%@",kServerAddress,suburl];
        url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [[RYDownloaderManager sharedManager] requestDataByGetWithURLString:url delegate:self purpose:kDeleteYuYueDownloaderKey];
        [[RYHUDManager sharedManager] showWithMessage:@"删除预约中..." customView:nil hideDelay:2.f];
    }
}
#pragma mark - RYDownloaderDelegate methods
- (void)downloader:(RYDownloader*)downloader completeWithNSData:(NSData*)data
{
    NSString *str = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    //去掉被包的jsonp字串
    if(str.length > 7)
        str = [str substringWithRange:NSMakeRange(6, str.length-7)];
    if([downloader.purpose isEqualToString:kYuYueListDownloaderKey])
    {
        NSDictionary *dict = [str JSONValue];
        if([[dict objectForKey:@"result"] isEqualToString:@"1"])
        {
            if(kCurrentPageNum == kInitPageNum)
                self.productOrders = [NSMutableArray array];
            NSArray *array = [dict objectForKey:@"list"];
            for(NSDictionary *dict in array)
            {
                NYProductOrder *nypo = [[NYProductOrder alloc] init];
                for(NSString *key in [dict allKeys])
                {
                    @try {
                        [nypo setValue:[dict objectForKey:key] forKey:key];
                    }
                    @catch (NSException *exception) {
                        NSLog(@"试图添加不存在的key: %@到NYProductOrder实例中.",key);
                    }
                }
                [self.productOrders addObject:nypo];
                [nypo release];
            }
            
            if(self.listType == kListAll)
            {
                if(array.count == kNumOfPage)
                    self.yuyueTableView.tableFooterView = self.moreView;
                else
                    self.yuyueTableView.tableFooterView = nil;
            }
            else
            {
                if(array.count == kAllNumOfPage)
                    self.yuyueTableView.tableFooterView = self.moreView;
                else
                    self.yuyueTableView.tableFooterView = nil;
            }
            
            [self filterList];
            
            [self.yuyueTableView reloadData];
        }
        else
        {
            [[RYHUDManager sharedManager] showWithMessage:[dict objectForKey:@"message"] customView:nil hideDelay:2.f];
            self.yuyueTableView.tableFooterView = nil;
        }
        if(self.filterOrders.count == 0)
        {
            self.placeHolderImageView.image = [UIImage imageNamed:@"nodata.png"];
            self.placeHolderImageView.hidden = NO;
            self.yuyueTableView.hidden = YES;
        }
        else
        {
            self.placeHolderImageView.hidden = YES;
            self.yuyueTableView.hidden = NO;
        }
    }
    else
    {
        NSDictionary *dict = [str JSONValue];
        if([[dict objectForKey:@"result"] isEqualToString:@"1"])
        {
            //删除成功之后删除tableview的cell
            NSInteger index = 0;
            for(NYProductOrder *nypo in self.productOrders)
            {
                if([nypo.sf_opportunity_id isEqualToString:self.deleteId])
                {
                    break;
                }
                index++;
            }
            [self.productOrders removeObjectAtIndex:index];
            
            [self filterList];
            [self.yuyueTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
            [[NSNotificationCenter defaultCenter] postNotificationName:kRefreshOnlneProductsNotification object:nil];
        }
        [[RYHUDManager sharedManager] showWithMessage:[dict objectForKey:@"message"] customView:nil hideDelay:2.f];
    }
}
- (void)downloader:(RYDownloader*)downloader didFinishWithError:(NSString*)message
{
    if([downloader.purpose isEqualToString:kYuYueListDownloaderKey])
    {
        if(self.filterOrders.count == 0)
        {
            self.placeHolderImageView.image = [UIImage imageNamed:@"nodata.png"];
            self.placeHolderImageView.hidden = NO;
            self.yuyueTableView.hidden = YES;
        }
        else
        {
            self.placeHolderImageView.hidden = YES;
            self.yuyueTableView.hidden = NO;
        }
        [[RYHUDManager sharedManager] showWithMessage:kNetWorkErrorString customView:nil hideDelay:2.f];
    }
    else
    {
        [[RYHUDManager sharedManager] showWithMessage:kNetWorkErrorString customView:nil hideDelay:2.f];
    }
}

@end
